import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { wrapperEnv } from './build'
import { createHtmlPlugin } from 'vite-plugin-html'
import { viteMockServe } from 'vite-plugin-mock' // 引入 mock 插件提供的方法

// 路径查找
const pathResolve = (dir: string): string => {
  return resolve(__dirname, '.', dir)
}

// 设置别名，还可以添加其他路径
const alias: Record<string, string> = {
  '@': pathResolve('src'),
  '@views': pathResolve('src/views'),
  '@store': pathResolve('src/store/modules'),
  '@comp': pathResolve('src/components')
}

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  const viteEnv = wrapperEnv(env)

  return {
    base: viteEnv.VITE_PUBLIC_PATH,
    plugins: [
      vue(),
      createHtmlPlugin({
        inject: {
          data: {
            //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
            title: viteEnv.VITE_APP_TITLE
          }
        }
      }),
      // mock 配置项
      viteMockServe({
        mockPath: './src/mock',
        localEnabled: true, // 开发环境
        prodEnabled: false, // 生产环境设为true，也可以根据官方文档格式
        logger: false,
        supportTs: true
      })
    ],
    resolve: {
      alias
    },
    server: {
      host: '0.0.0.0',
      port: viteEnv.VITE_PORT,
      open: true,
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: {
        '/omo/': {
          target: 'http://127.0.0.1:8095',
          changeOrigin: true
          // rewrite: (path) => path.replace(/^\/api/, '')
        },
        '/hik/': {
          target: 'http://127.0.0.1:8095',
          changeOrigin: true
          // rewrite: (path) => path.replace(/^\/api/, '')
        },
        '/tdengine/': {
          target: 'http://127.0.0.1:8091',
          changeOrigin: true
          // rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    }
  }
})
